var xlsx = require('node-xlsx');
var fs = require('fs');
var path = require("path");
const typeIndex = 1//类型索引
const notationIndex = 2//注释索引
const keyIndex = 3//key索引
const dataStart = 4 //数据从第几个开始算
const tableUrl = path.resolve(__dirname, './Config.xlsx')//文件路径
/**
 * 生成提示文件跟json
 */
class changTool {
    constructor() {
        let result = this.parseXlsxOne(tableUrl)
        this.writeTs(result)
        console.log(result)
    }
    /**
     * 解析单张表
     * @param url 
     */
    parseXlsxOne(url) {
        const workSheetsFromFile = xlsx.parse(fs.readFileSync(url));
        let xlsxName = url.replace(/(.*\/)*([^.]+).*/ig, "$2")
        let contentNamespace = ''
        let arrBiao = []
        let arrType = []
        let arrArrKey = []
        workSheetsFromFile.forEach(biaoOne => {
            let contentSheet = ''
            let biaoOneData = biaoOne.data
            let len = biaoOneData[keyIndex].length//数据的个数以key为准
            for (let i = 0; i < len; i++) {
                let notation = biaoOneData[notationIndex][i]
                let key = biaoOneData[keyIndex][i]
                let type = biaoOneData[typeIndex][i]
                contentSheet += this.templateDetailed(notation, key, type)
            }
            let allKey = []
            for (let i = dataStart, len = biaoOneData.length; i < len; i++) {
                let hengOne = biaoOneData[i]
                if (!(hengOne && hengOne.length > 0)) {
                    continue;
                }
                allKey.push(hengOne[0])
            }
            contentSheet = this.removeLineBreaks(contentSheet)
            contentNamespace += this.templateSheet(biaoOne.name, contentSheet)
            arrBiao.push(biaoOne.name)
            arrType.push(biaoOneData[typeIndex][0])
            arrArrKey.push(allKey)
        })
        contentNamespace += this.templateConfigData(xlsxName, arrBiao, arrType, arrArrKey)
        contentNamespace = this.removeLineBreaks(contentNamespace)
        contentNamespace = this.templateReadCode(contentNamespace)
        return contentNamespace
    }
    /**
     * 写入代码提示
     */
    writeTs(str) {
        fs.writeFileSync(path.resolve(__dirname, '../../Assets/Scripts/MyUnityJson.cs'), str)
    }
    /**
     * 生成单个分页
     */
    templateSheet(className, content) {
        let str =
            `/// <summary>
/// ${className}
/// </summary>
[Serializable]
public class ${className} {
        ${content}
}
`
        return str
    }
    /**
     * 生成详情
     */
    templateDetailed(notation, keyName, type) {
        let str =
            `/// <summary>
        /// ${notation}
        /// </summary>
        public ${type} ${keyName};
        `
        return str
    }
    /***
     * 生成总数据类型
     */
    templateConfigData(biaoName, arrBiao, arrType, arrArrKey) {
        let arrBiaoStr = '';
        arrBiao.forEach((one, index) => {
            arrBiaoStr +=
                `public Dictionary<${arrType[index]}, ${one}> ${one};
    public ${arrType[index]}[] ${one}KeyList = {${arrArrKey[index].join(",")} };
    `
        })
        arrBiaoStr = this.removeLineBreaks(arrBiaoStr)
        let str =
            `/// <summary>
/// ${biaoName}
/// </summary>
[Serializable]
public class ConfigData
{
	${arrBiaoStr}
}
`
        return str
    }
    /**
     * 生成读取代码
     */
    templateReadCode(content) {
        let str =
            `using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
${content}
public class MyJson
{
	public static ConfigData config;
	public static void Init()
	{
		string str = ReadFromStreamAssets("myJson.json");
		config = JsonConvert.DeserializeObject<ConfigData>(str);
	}
    private static string ReadFromStreamAssets(string jsonFilePath)
    {
        var fullPath = GetFilePathOfStreamingAssetsPath(jsonFilePath);
#if UNITY_ANDROID && !UNITY_EDITOR
            WWW www = new WWW(fullPath);
            if (www.error != null) {
                Debug.LogError("error : " + fullPath);
                return "";
            }
            while (!www.isDone) { }
            return www.text;
#else
        StreamReader reader = new StreamReader(fullPath);
        if (reader != null) {
            var ret = reader.ReadToEnd();
            reader.Close();
            return ret;
        } else {
            throw new System.Exception();
        }
#endif
    }
    private static string GetFilePathOfStreamingAssetsPath(string filePath)
    {
        return UnityEngine.Application.streamingAssetsPath + Path.DirectorySeparatorChar + filePath;
    }
}`
        return str
    }
    /**
     * 去除换行
     * @param content 
     */
    removeLineBreaks(content) {
        return content.substr(0, content.lastIndexOf('\n'));
    }
}
/**
 * 生成json数据
 */
class loadAndCheckXlsx {
    constructor() {
        let jsonData = this.parseXlsxOne(tableUrl)
        this.writeJson(JSON.stringify(jsonData))
    }
    /**
     * 解析单张表生成json
     * @param url 
     */
    parseXlsxOne(url) {
        const workSheetsFromFile = xlsx.parse(fs.readFileSync(url));
        let result = {}
        workSheetsFromFile.forEach((biaoOne, biaoIndex) => {
            let json = {}
            let biaoOneData = biaoOne.data
            let arrKey = biaoOneData[keyIndex]
            let arrType = biaoOneData[typeIndex]
            for (let i = dataStart, len = biaoOneData.length; i < len; i++) {
                let hengOne = biaoOneData[i]
                if (!(hengOne && hengOne.length > 0)) {
                    continue;
                }
                let data = {}
                for (let j = 0; j < arrKey.length; j++) {
                    if (arrType[j] == "bool") {
                        data[arrKey[j]] = !!hengOne[j]
                    } else {
                        data[arrKey[j]] = hengOne[j]
                    }
                }
                json[data[arrKey[0]]] = data
            }
            result[biaoOne.name] = json;
        })
        return result
    }
    /**
     * 生成代码
     */
    writeJson(str) {
        fs.writeFileSync(path.resolve(__dirname, '../../Assets/StreamingAssets/myJson.json'), str)
        console.log("生成json成功")
    }
}
(function () {
    new changTool()
    new loadAndCheckXlsx()
}())